package com.agv.backend.service.impl;

import com.agv.backend.entity.pojo.AgvTask;
import com.agv.backend.entity.pojo.AgvUser;
import com.agv.backend.mapper.AgvTaskMapper;
import com.agv.backend.mapper.AgvUserMapper;
import com.agv.backend.service.AgvUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.agv.backend.service.AgvTaskService.STATUS_PATROLLING;

@Service
@Slf4j
public class AgvUserServiceImpl extends ServiceImpl<AgvUserMapper, AgvUser> implements AgvUserService {

    private final AgvUserMapper agvUserMapper;
    private final AgvTaskMapper agvTaskMapper;

    public AgvUserServiceImpl(AgvUserMapper agvUserMapper, AgvTaskMapper agvTaskMapper) {
        this.agvUserMapper = agvUserMapper;
        this.agvTaskMapper = agvTaskMapper;
    }

    @Override
    public AgvUser getUserByName(String name) {
        AgvUser user = agvUserMapper.selectOne(new LambdaQueryWrapper<AgvUser>().eq(AgvUser::getName, name));
        if (user == null) {
            log.warn("User with name {} not found", name);
        } else {
            log.info("Retrieved user: {}", user);
        }
        return user;
    }

    @Override
    public List<AgvUser> getUsers(List<String> userNames) {
        QueryWrapper<AgvUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("name", userNames);
        List<AgvUser> users = agvUserMapper.selectList(queryWrapper);
        log.info("Retrieved users: {}", users);
        if(users == null || users.isEmpty()){
            return List.of();
        }

        LambdaQueryWrapper<AgvTask> lambdaQueryWrapper = new LambdaQueryWrapper<AgvTask>().eq(AgvTask::getTaskStatus, STATUS_PATROLLING);
        List<AgvTask> agvTasks = agvTaskMapper.selectList(lambdaQueryWrapper);
        AgvTask agvTask = null;
        if(agvTasks != null && !agvTasks.isEmpty()){
            agvTask = agvTasks.get(0);
        }

        if(agvTask != null){
            agvTask.setExecutor(users.get(0).getName());
            agvTaskMapper.updateById(agvTask);
            log.info("update success");
        }else {
            log.info("update failed");
        }

        return users;
    }
}